﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApplicationCore.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Web.Services;
using Web.ViewModels;
using Infrastructure;

namespace Web.Hubs
{
	[Authorize]
	public class Chat : HubWithPresence
	{
		private IUserTracker<Chat> _userTracker;
		private readonly IRoomService _roomService;
		private readonly IChatMsgService _service;

		public Chat(IUserTracker<Chat> userTracker, IRoomService roomService, IChatMsgService  chatMsgService)
			: base(userTracker)
		{
			_userTracker = userTracker;
			   _roomService = roomService;
			_service = chatMsgService;
		}

		public override async Task OnConnectedAsync()
		{  
			await Clients.Client(Context.ConnectionId).InvokeAsync("SetUsersOnline", await GetUsersOnline());

			await base.OnConnectedAsync();
		}
		[TypeFilter(typeof(AddLoginLogWithFactoryAttribute), Arguments = new object[] { OptType.ChatJoined })]
		public override Task OnUsersJoined(UserDetails[] users)
		{
			return Clients.Client(Context.ConnectionId).InvokeAsync("UsersJoined", users);
		}
		[TypeFilter(typeof(AddLoginLogWithFactoryAttribute), Arguments = new object[] { OptType.ChatLeft})]
		public override Task OnUsersLeft(UserDetails[] users)
		{  
			return Clients.Client(Context.ConnectionId).InvokeAsync("UsersLeft", users);
		}

		public async Task Send(string message,int roomId,string toUserId)
		{
			await Groups.AddAsync(Context.ConnectionId, "" + roomId);
			var re=await _service.SendChatMsg(message, roomId, Context.User.Identity.Name,toUserId);
			 if(re!=null)
			await Clients.Group(""+ roomId).InvokeAsync("Send", Context.User.Identity.Name, message, 
				toUserId,DateTime.Now.DateTimeFormat( DateFormatType.defalut1));
		}

		public async Task JoinGroup(string roomid)
		{
			//await Groups.AddAsync(Context.ConnectionId, ""+roomid);

			//await Clients.Group(roomid).InvokeAsync("Send", $"{Context.ConnectionId} joined {roomid}");
		}
	}
}
